<template>
  <img src="@/assets/bg.jpg" alt="登录背景图" class="bg-img">
  <el-row :gutter="0" justify="space-between" align="middle" style="height: 100vh;">
    <el-col :span="2">
      <el-card @click="router.push('/search')" style="cursor: pointer;">
        <el-row align="middle" justify="center" style="height: 60vh;">
          <div style="width: 40px;font-size: 40px;font-weight: bold;color: #0753a2;height: auto;">
            寻找书本
          </div>
        </el-row>
      </el-card>
    </el-col>
    <el-col :span="13">
      <el-card style="min-height: 60vh;">
        <div>
          <h2>用户登录</h2>
          <h3>智阅图书云借还管理系统</h3>
        </div>
        <el-form
            style="padding-right: 60px"
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-width="60px"
            label-position="right"
        >
          <el-form-item label="账号" prop="acc">
            <el-input size="large" placeholder="请输入账号/电话" v-model="ruleForm.acc" type="text" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="密码" prop="pwd">
            <el-input size="large" placeholder="请输入密码"
                      v-model="ruleForm.pwd"
                      type="password"
                      autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-row style="width: 100%">
              <el-col :span="19">
                <el-input size="large" v-model="ruleForm.code" placeholder="请输入验证码"/>
              </el-col>
              <el-col :span="5">
                <div class="code">
                  <img :src="codeSrc" alt="code" @click="getCode" style="cursor: pointer;">
                </div>
              </el-col>
            </el-row>
            <el-row style="width: 100%;height: 1px;transform: translateY(-20px);">
              <el-col :span="19"></el-col>
              <el-col :span="5">
                <div class="code">
                  <el-link type="info" :underline="false" @click="getCode"
                           style="color: #0753a2;font-size: 14px;">
                    看不清 换一张
                  </el-link>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" @click="submitForm(ruleFormRef)">
              登录
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="large" @click="resetForm(ruleFormRef)">清空</el-button>
          </el-form-item>
          <el-row justify="end" align="middle">
            <el-link :underline="false" type="primary" @click="ForgetVisible = true">忘记密码，前往找回密码</el-link>
          </el-row>
          <el-row justify="end" align="middle" style="margin-top: 10px;">
            <el-link :underline="false" type="primary" @click="RegistVisible = true">还没有账号，前往注册</el-link>
          </el-row>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="2">
      <el-card @click="router.push('/guide')" style="cursor: pointer;">
        <el-row align="middle" justify="center" style="height: 60vh;">
          <div style="width: 40px;font-size: 40px;font-weight: bold;color: #0753a2;height: auto;">
            使用指南
          </div>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <!--  忘记密码  -->
  <dialog-forget v-model:visible="ForgetVisible"/>
  <!--  注册账号  -->
  <dialog-regist v-model:visible="RegistVisible"/>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {ElMessage} from "element-plus";
import router from "@/router";
import api from "@/api";
import {index} from "@/store";
import DialogForget from '@/components/dialog/DialogForget.vue'
import DialogRegist from '@/components/dialog/DialogRegist.vue'

const ForgetVisible = ref(false)
const RegistVisible = ref(false)
onMounted((() => {
  localStorage.setItem("keypath", '0');
  getCode();
}))
const codeSrc = ref('');

function getCode() {
  api.login.generateImageCode().then((res: any) => {
    const bufferUrl = btoa(
        new Uint8Array(res).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ""
        )
    );
    codeSrc.value = "data:image/png;base64," + bufferUrl;
  });
}

const ruleFormRef = ref<FormInstance>()

const validateAcc = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  }
  callback()
}
const validatePwd = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  }
  callback()
}
const checkCode = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入验证码'))
  }
  callback()
}

const ruleForm = reactive({
  acc: '',
  pwd: '',
  code: '',
})

const rules = reactive<FormRules>({
  acc: [{validator: validateAcc, trigger: 'blur'}],
  pwd: [{validator: validatePwd, trigger: 'blur'}],
  code: [{validator: checkCode, trigger: 'blur'}],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  //@ts-ignore
  formEl.validate((valid) => {
    if (valid) {
      api.login.login(ruleForm.acc, ruleForm.pwd, ruleForm.code).then((res: any) => {
        if (!res.success) {
          ruleForm.code = "";
          getCode();
        }
        ElMessage({message: res.message, type: res.success ? 'success' : 'error', grouping: true, showClose: true});
        localStorage.setItem("user", JSON.stringify(res.data.user));
        localStorage.setItem("role", JSON.stringify(res.data.role));
        localStorage.setItem("menu", JSON.stringify(res.data.menu));
        localStorage.setItem("token", JSON.stringify(res.data.token));
        index().setToken(res.data.token);
        localStorage.setItem("keypath", "0");
        router.push("/home");
      })
    } else {
      ElMessage.warning({message: "请填写表单", grouping: true, showClose: true});
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
.bg-img {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
}

:deep(.el-card) {
  width: auto;
  background-color: rgba(255, 255, 255, .6);
}

h2, h3 {
  text-align: center;
  color: #0753a2;
  font-size: 28px;
}

h3 {
  margin: 10px 0;
  font-size: 22px;
}

img[alt='code'] {
  height: 40px;
  margin-top: 2px;
}

:deep(.el-button) {
  width: 100%;
}
</style>